<template>
	<view class="app-public-user">
		<view class="u-flex-xy-center u-p-t-180">
			<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
				<load-image size="124rpx" mode="aspectFill" :mobile="false" :lazyLoad="false" shape="circle" :src="avatarUrl"></load-image>
				<view class="u-font-24 c-placeholder">更换头像</view>
			</button>
		</view>
		<view class="app-public-user__input u-flex-xy-center">
			<input v-model="nickname" type="nickname" class="weui-input" :placeholder="$t('public.请输入您的昵称')" />
		</view>
		<view class="u-p-t-48 u-p-l-60 u-p-r-60">
			<button type="primary" class="h-80" shape="circle" size="large" :loading="isLoading" :throttleTime="1000" @click="submit">{{ $t('common.确认') }}</button>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { uploadFilePath, editNickName } from '@/common/request/api';
import { useCurrentInstance } from '@/common/hooks';
import { page } from '@/common/utils'
import { useInit } from '@/common/stores';

const props = defineProps({
	sessionKey: String
});

const ctx = useCurrentInstance();
const {setTabbarPageIndex} = useInit()

const nickname = ref('');
const avatarUrl = ref('/pages/public/static/public/avatar.png');

const onChooseAvatar = (e:{detail:{url:string}}) => {
	const { avatarUrl: url } = e.detail;
	avatarUrl.value = url;
};

const submit = async () => {
	if (!nickname.value) {
		ctx.$toastApp(ctx.$t('public.请输入您的昵称'));
		return;
	}
	let avatar = avatarUrl.value;
	if (avatar !== '/pages/public/static/public/avatar.png') {
		let data = await uploadFilePath(avatarUrl.value);
		avatar = data.data.url;
	} else {
		avatar = '';
	}
	editNickName({
		headUrl: avatar,
		nickname: nickname.value
	}).then((_res) => {
		
		const pagesPath = page(2)
		if (!pagesPath||pagesPath === '/' || pagesPath === 'pages/public/account/user') {
			setTabbarPageIndex(0);
			ctx.$switchTab('/pages/tabbar/index');
		} else {
			ctx.$back();
		}
	});
};
</script>

<style lang="scss" scoped>
.u-p-t-180 {
	margin-top: 150rpx;
}
.app-public-user {
	&__input {
		padding-top: 94rpx;
		input {
			width: 630rpx;
			height: 100rpx;
			background: #ffffff;
			border-radius: 20rpx;
			border: 2rpx solid #dddddd;
			padding-left: 30rpx;
		}
	}
}
.h-80 {
	height: 90rpx;
	color: #ffffff;
}
</style>
